<?php

namespace common\repositories\cms;

use Yii;
use common\repositories\BaseRepository;
use common\entities\cms\ArticleEntity;
use common\support\StringHelper;
use common\support\Helper;
use common\error\ErrorCode;

class ArticleRepository extends BaseRepository {

    const ARTICLE_RELEASE = 1; // 发布
    const ARTICLE_NO_RELEASE = 0; // 未发布
    const ARTICLE_DEL = 1; // 删除
    const ARTICLE_NO_DEL = 0; // 未删除
    const ARTICLE_TOP = 1; // 头版
    const ARTICLE_NO_TOP = 0; // 非头版
    
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 文章pv
     * @param type $articleId
     * @return boolean
     */
    public function updatePv($articleId) {
        $entity = ArticleEntity::find()->where(["a_id"=>$articleId])->one();
        if(is_null($entity))return false;
        $entity->pv = $entity->pv+1;
        $entity->save();
        return true;
    }
    
    /**
     * 
     * @param type $id
     */
    public function updateShareNum ($id) {
        $entity = ArticleEntity::find()->where(["a_id"=>$id])->one();
        if(is_null($entity))return false;
        $entity->share_num = $entity->share_num+1;
        $entity->save();
        return true;        
    }
    
    /**
     * 更新文章
     * @param type $model
     */
    public function updateArticle ($model) {
        $entity = ArticleEntity::find()->where(['a_id' => $model->aId])->one();
        if (!isset($entity)) {
            return self::setAndReturn(ErrorCode::ERR_CMS_ARTICLE_NOT_EXISTS); // 文章不存在
        }
        $model->modifiedTime = time();
        $this->setFieldEntity($entity, $model);
        $result = $entity->update();
        if ($result === false) {
            return self::setAndReturn(ErrorCode::ERR_CMS_ARTICLE_SAVE_FAIL, $entity->firstErrorMessage); // 保存错误
        } else {
            return $entity->a_id;
        }
        
    }
    
    /**
     * 创建文章
     * @param type $model
     */
    public function addArticle ($model) {
        $model->createdTime = time();
        $model->modifiedTime = time();  
        
        $entity = new ArticleEntity();
        $this->setFieldEntity($entity,$model);
        $entity->created_time = $model->createdTime;

        $result = $entity->save();
        if (false === $result) {
            return self::setAndReturn(ErrorCode::ERR_CMS_ARTICLE_SAVE_FAIL, $entity->firstErrorMessage); // 保存错误
        }
        return $entity->a_id;
    }
    
    /**
     * 设置数据
     * @param type $entity
     * @param type $model
     */
    public function setFieldEntity(&$entity,$model) {
        $entity->modified_time = $model->modifiedTime;
        $entity->modified_by = $model->modifiedBy;
        $entity->title = $model->title;
        $entity->pv = empty($model->pv) ? 0 : $model->pv;
        $entity->collect = empty($model->collect) ? 0 : $model->collect;
        $entity->content = htmlspecialchars($model->content);
        $entity->tag = $model->tag;  
        $entity->image_url = $model->imageUrl;
        $entity->file_url = $model->fileUrl;
        $entity->dir_id = $model->dirId;
        $entity->file_name = $model->fileName;
        $entity->link_url = $model->linkUrl;
        $entity->author = $model->author;


        $entity->abstract_mode = $model->abstractMode ? $model->abstractMode : 0;
        $entity->abstract = $model->abstract ? htmlspecialchars($model->abstract) : null;
        $entity->first_visit_show = $model->firstVisitShow ? $model->firstVisitShow : 0;
        $entity->period_visit_show = $model->periodVisitShow ? $model->periodVisitShow : 0;

        $entity->period_start_time = "1990-01-01 00:00:00";//此时间无用的，只是以前逻辑是如果为空则会提示，所以设置一个固定时间作为升级用
        $entity->period_end_time = "1990-01-01 00:00:00";//此时间无用的，只是以前逻辑是如果为空则会提示，所以设置一个固定时间作为升级用

        $entity->g0_period_start_time = $model->periodStartTime ? $model->periodStartTime : null;
        $entity->g0_period_end_time = $model->periodEndTime ? $model->periodEndTime : null;

        $entity->g2_period_start_time = $model->g2PeriodStartTime ? $model->g2PeriodStartTime : null;
        $entity->g2_period_end_time = $model->g2PeriodEndTime ? $model->g2PeriodEndTime : null;

        $entity->close_time = $model->closeTime ? $model->closeTime : null;
    }
    
    public function getArticleInfo ($aId)
    {
        $query = ArticleEntity::find()
            ->where(['a_id' => $aId])
            ->asArray()
            ->one();

        if (!empty($query)) {
            $query['content'] = htmlspecialchars_decode($query['content']);
            $query['abstract'] = htmlspecialchars_decode($query['abstract']);
            $query['period_start_time'] = $query['g0_period_start_time'];
            $query['period_end_time'] = $query['g0_period_end_time'];
        }

        return $query;
    }

    /**
     * 获取文章列表
     * @param $sidx 排序字段
     * @param $sord 排序规则
     * @param $page 当前页码
     * @param $page_size 每页条数
     * @param $search 搜索关键字
     * @param $updatedirIds 更新墙目录列表
     * @return $query 文章列表
     */
    public function getArticleAllList ($sidx, $sord, $page, $page_size, $search="", $updateDirIds) {
        $ascText = strtolower($sord) == 'asc' ? SORT_ASC : SORT_DESC;
        $query = ArticleEntity::find();
            
        if (! empty($search)) {
            $query = $query->where(['like', 'title', $search])
                ->orwhere(['like', 'tag', $search]);
        }
        $articleList = $query->andwhere(['del' => 0])
            ->andWhere(['not in', 'dir_id', $updateDirIds])
            ->orderBy([$sidx => $ascText])
            ->offset((int)($page-1)*$page_size)
            ->limit((int)$page_size)                
            ->all();
        return $articleList;
    }


    public function getArticleListByDirId($dirId,$limit=10) {

        $connection = ArticleEntity::getDb();
        $sql = "select a_id,dir_id,tag,title,image_url,file_url,IF(`content` = '' or `content` is null, 1 ,0) as is_empty from ".ArticleEntity::tableName()."
        where dir_id={$dirId} and del=".self::ARTICLE_NO_DEL." and status=".self::ARTICLE_RELEASE." order by sort desc,modified_time desc limit {$limit}";
        $command = $connection->createCommand($sql);
        $result = $command->queryAll();
        return $result;

//        $entity = ArticleEntity::find()->select("a_id,dir_id,tag,title,image_url,file_url,IF(`content` = '' OR `content` IS NULL , 0 ,1) as is_empty")
//            ->where(["dir_id"=>$dirId,"del"=>self::ARTICLE_NO_DEL,'status'=>self::ARTICLE_RELEASE])
//            ->orderBy('sort desc,modified_time desc')
//            ->limit($limit)
//            ->all();
//        return $entity;
    }
    
    /**
     * 批量处理
     * @param type $section
     * @param type $value
     * @param type $ids
     * @return type
     */
    public function updateBatch($section, $value, $ids,$insideArr,$outsideArr) {
        foreach($ids as $id){
            $entity = ArticleEntity::find()
                ->where(['a_id'=>$id])
                ->one();
            $entity->$section = $value;
            $entity->inside=$insideArr[$id];
            $entity->outside=$outsideArr[$id];
            $entity->save();
        }

//        $entitys = ArticleEntity::find()
//                ->where(['in', 'a_id', $ids])
//                ->all();
//        foreach ($entitys as $entity) {
//            $entity->$section = $value;
//            $entity->save();
//        }
//
    }

    public static function existsArticleByDirId($dirId) {
        return ArticleEntity::find()
            ->where(['dir_id'=>$dirId])
            ->exists();
    }

    /**
     * 删除附件
     * @param $a_id string 文章ID
     * @param $url string 发奖URL
     * @return bool
     */
    public function  fujianDel($a_id, $url)
    {
        $urlHead = substr($url, 0, 49);
        $urlLast = substr($url, 49);
        $urlLast = urlencode($urlLast);
        $articleEntity = ArticleEntity::find()->select('a_id,title,file_url,file_name')->where(["a_id" => $a_id])->one();
        if (is_null($articleEntity)) {
            return false;
        }
        $urls = explode("@@", $articleEntity->file_url);
        $names = explode("@@", $articleEntity->file_name);
        foreach ($urls as $k => $v) {
            if ($v == $urlHead . $urlLast) {
                unset($names[$k]);
            }
        }
        $names = implode("@@", $names);
        $articleEntity->file_name = $names;
        $articleEntity->file_url = str_replace('@@' . $urlHead . $urlLast, '', $articleEntity->file_url);
        $res = $articleEntity->save();
        if ($res === false) {
            return false;
        }
        return true;
    }

    /**
     * 获取更新说明文章列表
     * @param $sidx string 排序字段
     * @param $sord string 排序规则
     * @param $page int 页码
     * @param $page int 每页条数
     * @param $search string 搜索关键字
     * @param $updateDirIds 更新墙目录列表
     * @return srticleList array 文章列表
     */
    public function getUpdateArticleList($sidx, $sord, $page, $page_size, $search = "", $updateDirIds)
    {
        $ascText = strtolower($sord) == 'asc' ? SORT_ASC : SORT_DESC;
        $query = ArticleEntity::find();

        if (!empty($search)) {
            $query = $query->where(['like', 'title', $search])
                ->orwhere(['like', 'tag', $search]);
        }
        $articleList = $query->andwhere(['del' => 0])
            ->andwhere(['in', 'dir_id', $updateDirIds])
            ->orderBy([$sidx => $ascText])
            ->offset((int)($page - 1) * $page_size)
            ->limit((int)$page_size)
            ->all();
        return $articleList;
    }

    /**
     * @param $id 文章id
     * @param $attrArray 修改字段
     * @return bool
     */
    public function updateQuickSet($id, $attrArray){
        $articleEntity = ArticleEntity::find()->select("a_id,title,status")->where(['a_id'=>$id])->one();
        if (empty($articleEntity)){
            return false;
        }
        foreach ($attrArray as $k => $v){
            $articleEntity->$k = $v;
        }
        return $articleEntity->save();
    }
}